import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:km_printer_plugin/km_printer_plugin.dart';
import 'package:permission_handler/permission_handler.dart';

class EventChannelConstant {
  static const int BONDED_DEVICES = 99; //已绑定的蓝牙设备
  static const int FOUND_DEVICES = 1; //搜索到蓝牙设备
  static const int START_SCAN = 2; //开始扫描
  static const int STOP_SCAN = 3; //开始扫描
  static const int STATE_CONNECTED = 4; //蓝牙状态改变，连接上了蓝牙
  static const int STATE_DISCONNECTED = 5; //蓝牙状态改变，蓝牙连接断开
  static const int GATT_SERVICES_DISCOVERED = 6; //发现可用的蓝牙服务
  static const int DOES_NOT_SUPPORT_UART = 7; //服务或特征值不可用
  static const int DATA_AVAILABLE = 8; //收到蓝牙设备发送的数据
  static const int BLUETOOTH_OFF = 9; //蓝牙关闭通知
  static const int BLUETOOTH_ON = 10; //蓝牙开启通知
  static const int STATE_RECONNECTED = 11; //蓝牙状态改变，重连上了之前的蓝牙，不需要发现服务
  static const int SERVICE_CHARACTERISTICS = 12; //发现服务及其子特征值
  static const int BLUE_INFO = 111; //蓝牙名称、地址信息
}

class BluetoothScan extends StatefulWidget {
  const BluetoothScan({Key? key}) : super(key: key);
  @override
  _BluetoothScanState createState() => _BluetoothScanState();
}

class _BluetoothScanState extends State<BluetoothScan> {
  String _scanText = '搜索';
  List _bondedList = [];
  List _deviceList = [];
  Map _bluInfo = {};

  final KmPrinter _kmPrinter = KmPrinter();

  final TextEditingController _blueNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 监听蓝牙，处理显示数据
    _kmPrinter.kmReceiver.listen((data) {
      _streamDataProcess(data);
    });
    _requestPermissionAndStartScan();
  }

  @override
  void dispose() {
    super.dispose();
    if (_blueNameController != null) {
      _blueNameController.dispose();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('蓝牙搜索'),
        centerTitle: true,
      ),
      body: Container(
        child: ListView(
          children: [
            RaisedButton(
              child: Text(_scanText),
              onPressed: () {
                if (_scanText == '停止') {
                  _kmPrinter.stopScan();
                }
                if (_scanText == '搜索' || _scanText == '重新搜索') {
                  _kmPrinter.startScan();
                }
              },
            ),
            Container(
              child: Text('连接的蓝牙'),
            ),
            ListTile(
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('${_bluInfo['name']}'),
                  RaisedButton(
                    child: Text('修改设备名称'),
                    onPressed: () async {
                      // 弹窗-填写修改后的打印机名称
                      var dismiss = await showDialog<bool>(
                          context: context,
                          builder: (context) {
                            return AlertDialog(
                              title: Text('新的打印机名称'),
                              content: TextField(
                                controller: _blueNameController,
                              ),
                              actions: [
                                FlatButton(
                                  child: Text('确认'),
                                  onPressed: () =>
                                      Navigator.of(context).pop(true),
                                ),
                                FlatButton(
                                  child: Text('取消'),
                                  onPressed: () =>
                                      Navigator.of(context).pop(false),
                                ),
                              ],
                            );
                          });
                      if (dismiss != null && dismiss) {
                        if (_blueNameController.text.isNotEmpty) {
                          await _kmPrinter.changeBlueName({
                            'newName': _blueNameController.text,
                          });
                        } else {
                          print('没有输入打印机名称');
                        }
                      }
                    },
                  ),
                ],
              ),
              subtitle: Text('${_bluInfo['address']}'),
            ),
            Container(
              child: Text('已绑定设备'),
            ),
            Column(
              children: _bondedList
                  .map<Widget>((e) => ListTile(
                        title: Text('${e['name'] ?? ''}'),
                        subtitle: Text('${e['address']}'),
                        onTap: () async {
                          await _kmPrinter.openPrinter(e);
                          // Navigator.of(context).pop();
                        },
                      ))
                  .toList(),
            ),
            Container(
              child: Text('新设备'),
            ),
            Column(
              children: _deviceList
                  .map<Widget>((e) => ListTile(
                        title: Text('${e['name'] ?? ''}'),
                        subtitle: Text('${e['address']}'),
                        onTap: () async {
                          await _kmPrinter.connAndOpen(e);
                          // Navigator.of(context).pop();
                        },
                      ))
                  .toList(),
            ),
          ],
        ),
      ),
    );
  }

  _requestPermissionAndStartScan() async {
    PermissionStatus permissionStatus = await Permission.location.status;
    if (!permissionStatus.isLimited && _kmPrinter != null) {
      _kmPrinter.startScan();
    }
  }

  _streamDataProcess(data) {
    print('$data');
    switch (data['code']) {
      case EventChannelConstant.START_SCAN:
        setState(() {
          _scanText = '停止';
        });
        break;
      case EventChannelConstant.STOP_SCAN:
        setState(() {
          _scanText = '搜索';
        });
        break;
      case EventChannelConstant.STATE_CONNECTED:
        setState(() {
          _scanText = '重新搜索';
        });
        break;
      case EventChannelConstant.BONDED_DEVICES:
        setState(() {
          _bondedList = jsonDecode(data['data']);
        });
        break;
      case EventChannelConstant.FOUND_DEVICES:
        setState(() {
          _deviceList = jsonDecode(data['data']);
        });
        break;
      case EventChannelConstant.BLUE_INFO:
        setState(() {
          _bluInfo = jsonDecode(data['data']);
        });
        break;
    }
  }
}
